package com.qys.livesMall.security.interceptor.core;

import com.qys.livesMall.app.user.constants.RedisConstant;
import com.qys.livesMall.cache.RedisCache;
import com.qys.livesMall.cache.utils.CacheUtil;
import com.qys.livesMall.common.thread.ThreadContext;
import com.qys.livesMall.common.thread.holder.po.LoginUser;
import com.qys.livesMall.security.constants.SecConstants;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Locale;

import static com.qys.livesMall.common.constants.SysConstants.AUTHORIZATION;

@Order(4)
public class ThreadInterceptor implements HandlerInterceptor {
    private static Log logger = LogFactory.getLog(ThreadInterceptor.class);

    @Resource
    private RedisCache redisCache;

    //handle 前

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        logger.info("***********************执行了线程信息拦截器*************************");
        Locale locale=LocaleContextHolder.getLocale();
        ThreadContext.setLang(locale.getLanguage()+"_"+locale.getCountry());

        String token = request.getHeader(AUTHORIZATION);
        if (token == null) {
            return true;
        }

        String tokenKey = CacheUtil.getKey(SecConstants.RedisKeyPrefix.TOKEN, token);
        LoginUser userInfo = redisCache.getCacheObject(tokenKey);

        //查询是否app用户
        if (userInfo == null) {
            tokenKey = CacheUtil.getKey(RedisConstant.USER_TOKEN, token);
            userInfo = redisCache.getCacheObject(tokenKey);
        }

        //缓存未获取到用户数据
        if (userInfo == null) {
            //未登陆向前端返回数据
           return true;
        }

        //用户加入线程
        ThreadContext.addCurrentUser(userInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ThreadContext.remove();
    }

}

